﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI.WebControls;
using Meqs.Entity;
using Meqs.Entity.Parameters;
using Meqs.Logic;
using Meqs.Logic.Interface;
using Meqs.Utilities;

public partial class Credit_Teacher_ScoreInput_ScoreInput : ContainerBasePage
{
    #region 参数列表

    /// <summary>
    /// 学年
    /// </summary>
    protected static int SchoolYear
    {
        get
        {
            int year;
            if (int.TryParse(HttpContext.Current.Request["SchoolYear"], out year)) return year;
            return -1;
        }
    }

    /// <summary>
    /// 学期
    /// </summary>
    protected static int Term
    {
        get
        {
            int term;
            if (int.TryParse(HttpContext.Current.Request["Term"], out term)) return term;
            return -1;
        }
    }
    /// <summary>
    /// 学年
    /// </summary>
    protected static int Year
    {
        get
        {
            int year;
            if (int.TryParse(HttpContext.Current.Request["Year"], out year)) return year;
            return -1;
        }
    }

    /// <summary>
    /// 学期
    /// </summary>
    protected static int Month
    {
        get
        {
            int month;
            if (int.TryParse(HttpContext.Current.Request["Month"], out month)) return month;
            return -1;
        }
    }

    /// <summary>
    /// 班级ID
    /// </summary>
    protected static int ClsID
    {
        get
        {
            int clsID;
            if (int.TryParse(HttpContext.Current.Request["ClsID"], out clsID)) return clsID;
            return -1;
        }
    }

    private IList<ParamVal> _paramVals = new List<ParamVal>();
    protected IList<ParamVal> ParamVals
    {
        get
        {
            return _paramVals;
        }
        set
        {
            _paramVals = value;
        }
    }

    /// <summary>
    /// 计次
    /// </summary>
    protected string ScoreInputNumericHtmlStr
    {
        get
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<table style=\"width: 60px; height: 42px; border: 0px;\">");
            sb.AppendLine("    <tr>");
            sb.AppendLine("        <td>");
            sb.AppendLine("        	<input id=\"{0}\" oldvalue=\"{1}\" value=\"{1}\" maxlength=\"4\" Score=\"{2}\" MoralityType=\"2\" Math=\"{3}\" type=\"text\" class=\"txtStyle\" onfocusout=\"optionSettingScore(this, 2)\" style=\"height: 42px; width: 30px; text-align: center;\" />");
            sb.AppendLine("        </td>");
            sb.AppendLine("        <td style=\"display: none;\">");
            sb.AppendLine("        	<img src=\"../../Common/images/add_icon.gif\" onclick=\"add(this)\" style=\"cursor: hand;\" alt=\"\" />");
            sb.AppendLine("        	<img src=\"../../Common/images/minus_icon.gif\" onclick=\"minus(this)\" style=\"cursor: hand;\" alt=\"\" />");
            sb.AppendLine("        </td>");
            sb.AppendLine("    </tr>");
            sb.AppendLine("</table>");
            return sb.ToString();
        }
    }

    /// <summary>
    /// 计次
    /// </summary>
    protected string ScoreInputScoreHtmlStr
    {
        get
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<table style=\"width: 60px; height: 32px; border: 0px solid white;\">");
            sb.AppendLine("    <tr>");
            sb.AppendLine("        <td>");
            sb.AppendLine("             <input id=\"{0}\" oldvalue=\"{1}\" value=\"{1}\" maxlength=\"4\" MoralityType=\"1\" type=\"text\" class=\"txtStyle\" onfocusout=\"optionSettingScore(this, 1)\" style=\"height: 32px; width: 54px; text-align: center;");
            sb.AppendLine("                 float: left;\" />");
            sb.AppendLine("        </td>");
            sb.AppendLine("    </tr>");
            sb.AppendLine("</table>");
            return sb.ToString();
        }
    }

    /// <summary>
    /// 学科ID
    /// </summary>
    protected static int CauseID
    {
        get
        {
            int causeID;
            if (int.TryParse(HttpContext.Current.Request["CauseID"], out causeID)) return causeID;
            return -1;
        }
    }

    protected static GlobalCauseInfo Cause
    {
        get
        {
            if (CauseID == -1) return null;
            return Container<IGlobalCauseInfoLogic>.Instance.FindById(CauseID);
        }
    }

    protected bool IsModify
    {
        get
        {
            if (string.IsNullOrEmpty(HttpContext.Current.Request["Type"])) return false;
            return HttpContext.Current.Request["Type"].ToLower() == "edit";
        }
    }

    protected string ReportTitle
    {
        get
        {
            string title = "{0}{1} {2}{3}学分报表";

            int schoolYear = SchoolYear;
            int term = Term;
            if (SchoolYear == -1 || Term == -1)
            {
                ISchoolInfoLogic schLogic = Container<ISchoolInfoLogic>.Instance;
                SchoolInfo sch = schLogic.FindBySchoolMark(SchoolMark);
                schoolYear = sch.SchoolYear;
                term = sch.SchoolTerm;
            }
            string termStr = term == 1 ? "上学期" : "下学期";
            return string.Format(title, Common.ConvertSchoolYear(schoolYear), termStr, Cause == null ? "" : Cause.CauseName, Common.ReportDateType(3));
        }
    }

    protected static string ExcelFileName
    {
        get
        {
            string title = "{0}{1} {2}{3}学分报表";

            int schoolYear = SchoolYear;
            int term = Term;
            if (SchoolYear == -1 || Term == -1)
            {
                ISchoolInfoLogic schLogic = Container<ISchoolInfoLogic>.Instance;
                SchoolInfo sch = schLogic.FindBySchoolMark(SchoolMark);
                schoolYear = sch.SchoolYear;
                term = sch.SchoolTerm;
            }
            string termStr = term == 1 ? "上学期" : "下学期";
            string temp = string.Format(title, Common.ConvertSchoolYear(schoolYear), termStr, Cause == null ? "" : Cause.CauseName, Common.ReportDateType(3));
            return temp.Replace(" ","");
        }
    }

    protected string ReportSubTitle
    {
        get
        {
            string title = "班级：{0} &nbsp;&nbsp; 月份：{1}";
            IClsInfoLogic clsLogic = Container<IClsInfoLogic>.Instance;
            ClsInfo cls = clsLogic.FindById(ClsID);
            return string.Format(title, cls.ClsName, Year + "年" + Month + "月");
        }
    }

    private int _tableWidth;

    #endregion

    #region 绑定表格

    protected void BindHeadTable()
    {
        _tableWidth = 0;
        IStuCauseEvalTypeLogic mtLogic = Container<IStuCauseEvalTypeLogic>.Instance;
        IStuCauseEvalItemLogic miLogic = Container<IStuCauseEvalItemLogic>.Instance;
        IList<StuCauseEvalType> list;
        if (SchoolYear == -1 || Term == -1)
        {
            list = mtLogic.GetAllStuCauseEvalType(CauseID, SchoolMark);
        }
        else
        {
            list = mtLogic.GetAllStuCauseEvalType(CauseID, SchoolMark, SchoolYear, Term);
        }

        TableRow row = new TableRow();
        TableRow subRow = new TableRow();
        row.Style["background-color"] = "#D4F1F9";
        subRow.Style["background-color"] = "#D4F1F9";

        TableCell cell1 = new TableCell();
        cell1.Text = "学号";
        cell1.RowSpan = 2;
        cell1.CssClass = "FixedRowCol";
        cell1.Style["width"] = "50px";
        row.Cells.Add(cell1);
        _tableWidth += 40;

        TableCell cell2 = new TableCell();
        cell2.Text = "姓名";
        cell2.RowSpan = 2;
        cell2.CssClass = "FixedRowCol";
        cell2.Style["width"] = "60px";
        row.Cells.Add(cell2);
        _tableWidth += 100;

        int index = 0;
        foreach (StuCauseEvalType mt in list)
        {
            TableCell cell = new TableCell();
            cell.Text = mt.Caption;
            IList<StuCauseEvalItem> miList = miLogic.GetItemByType(SchoolMark, mt.RID);
            cell.ColumnSpan = miList.Count;
            cell.CssClass = "FixedRow";
            cell.Style["width"] = (60 * miList.Count) + "px";
            _tableWidth += 60 * miList.Count;
            foreach (StuCauseEvalItem item in miList)
            {
                TableCell subCell = new TableCell();
                subCell.Text = item.Caption + (item.Type == 1 ? String.Format("({0}分)", item.Param * item.Operator) : "(次)");
                subCell.CssClass = "FixedRow";
                subCell.Style["width"] = "60px";
                subCell.Attributes.Add("rName", item.Caption);
                subCell.Attributes.Add("index", index.ToString());
                subRow.Cells.Add(subCell);
                ParamVal pv = new ParamVal();
                pv.Index = index;
                pv.ItemID = item.RID;
                _paramVals.Add(pv);
                index++;
            }
            row.Cells.Add(cell);
        }
        TableCell cell3 = new TableCell();
        cell3.Text = "备注";
        cell3.RowSpan = 2;
        cell3.CssClass = "FixedRow";
        cell3.Style["width"] = "200px";
        row.Cells.Add(cell3);
        _tableWidth += 200;
        tblHead.Rows.Add(row);
        tblHead.Rows.Add(subRow);
        tblHead.Style["width"] = _tableWidth + "px";
    }

    protected void BindBodyTable()
    {
        IStudentInfoLogic sLogic = Container<IStudentInfoLogic>.Instance;
        IStuCauseEvalDetailLogic mdLogic = Container<IStuCauseEvalDetailLogic>.Instance;
        IStuCauseEvalRemarkLogic mrLogic = Container<IStuCauseEvalRemarkLogic>.Instance;
        IList<StudentInfo> stuList = null;
        if(SchoolCommon.Sch_SchoolInfo.SchoolYear == SchoolYear)
            stuList = sLogic.GetStudentByCls(SchoolMark, ClsID);
        else
            stuList = Container<IStudentHistoryLogic>.Instance.FindHistoryStudents(SchoolYear, Term, ClsID, SchoolMark);
        if(stuList == null)
            return;

        int i = 1;
        int j = 0;
        foreach (StudentInfo info in stuList)
        {
            TableRow row = new TableRow();
            TableCell cellSNo = new TableCell();
            if (j == 0) cellSNo.Style["border-top"] = "0px";
            cellSNo.Text = info.StudentCode;
            cellSNo.CssClass = "FixedCol";
            cellSNo.Style["width"] = "50px";
            cellSNo.Style["text-align"] = "right";
            row.Cells.Add(cellSNo);
            i++;

            TableCell cellSName = new TableCell();
            if (j == 0) cellSName.Style["border-top"] = "0px";
            cellSName.CssClass = "FixedCol";
            cellSName.Text = "&nbsp;" + info.StudentName;
            cellSName.Style["width"] = "60px";
            cellSName.Style["text-align"] = "left";
            row.Cells.Add(cellSName);

            IList<ScoreInputEntityWithCls> sieList = mdLogic.GetScoreInputEntityByStudent(info.RID, CauseID, ClsID, 3, Year, Month, SchoolYear, Term, SchoolMark);
            IList<ParamVal> pvList = new List<ParamVal>();
            foreach (ScoreInputEntityWithCls item in sieList)
            {
                ParamVal pv = new ParamVal();
                pv.ItemID = item.ItemID;
                if (!_paramVals.Contains(pv)) continue;
                ParamVal p = _paramVals[_paramVals.IndexOf(pv)];
                p.Type = item.Type;
                p.Param = item.Param;
                p.Score = item.Score;
                p.Operator = item.Operator;
                pvList.Add(p);
            }
            ListSort<ParamVal> sort = new ListSort<ParamVal>(pvList, "Index", true);
            pvList = sort.Sort();
            foreach (ParamVal pv in pvList)
            {
                TableCell subCell = new TableCell();
                if (j == 0) subCell.Style["border-top"] = "0px";

                subCell.Style["width"] = "60px";
                // 计次
                if (pv.Type == 2)
                {
                    // 可编辑状态
                    if (IsModify)
                    {
                        string html = string.Format(ScoreInputNumericHtmlStr, "txt_" + pv.ItemID + "_" + info.RID + "_2", pv.Param == 0 ? "" : pv.Param.ToString(), pv.Score, pv.Operator);
                        subCell.Text = html;
                        subCell.Attributes.Add("onmouseover", "try{mover(this);}catch(e){}");
                        subCell.Attributes.Add("onmouseout", "try{mout(this);}catch(e){}");
                    }
                    else
                    {
                        subCell.Text = pv.Param == 0 ? "" : pv.Param.ToString();
                        subCell.Style["text-align"] = "right";
                    }
                }
                // 计分
                if (pv.Type == 1)
                {
                    // 可编辑状态
                    if (IsModify)
                    {
                        string html = string.Format(ScoreInputScoreHtmlStr, "txt_" + pv.ItemID + "_" + info.RID + "_1", pv.Param == 0 ? "" : pv.Param.ToString(), pv.Score);
                        subCell.Text = html;
                    }
                    else
                    {
                        subCell.Text = pv.Param == 0 ? "" : pv.Param.ToString();
                        subCell.Style["text-align"] = "right";
                    }
                }

                row.Cells.Add(subCell);
            }

            // 备注
            StuCauseEvalRemark mr = mrLogic.GetRemarkByStudent(info.RID, CauseID, 3, Year, Month, SchoolYear, Term, SchoolMark);
            TableCell cellRemark = new TableCell();
            if (j == 0) cellRemark.Style["border-top"] = "0px";
            string span = "&nbsp;<span id=\"span_{0}\" title=\"{1}\">{2}</span>";
            span = string.Format(span, info.RID, mr == null ? "" : mr.Data, mr == null ? "" : mr.Data.Length > 20 ? mr.Data.Substring(0, 20) + "..." : mr.Data);
            cellRemark.Text = span;
            cellRemark.Attributes.Add("StudentID", info.RID.ToString());
            cellRemark.Attributes.Add("StudentName", info.StudentName);
            if (IsModify) cellRemark.Attributes.Add("onclick", "displayRemark(this)");
            cellRemark.Style["width"] = "200px";
            cellRemark.Style["text-align"] = "left";
            row.Cells.Add(cellRemark);
            tblHead.Rows.Add(row);
            tblHead.Style["width"] = _tableWidth + "px";
        }
    }

    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindHeadTable();
            BindBodyTable();
            ClientScript.RegisterStartupScript(GetType(), "script", "setTableHeight();", true);
        }
    }

    /// <summary>
    /// 保存单据
    /// </summary>
    /// <param name="jsonStr"></param>
    /// <param name="causeID"></param>
    /// <param name="clsID"></param>
    /// <param name="schoolYear"></param>
    /// <param name="term"></param>
    /// <param name="year"></param>
    /// <param name="month"></param>
    /// <returns></returns>
    [WebMethod]
    public static bool SaveScoreInput(string jsonStr, int causeID, int clsID, int schoolYear, int term, int year, int month)
    {
        try
        {
            IList<Items> list = ConvertJson(jsonStr);
            IStuCauseEvalSubmitRecordLogic scesrLogic = Container<IStuCauseEvalSubmitRecordLogic>.Instance;
            int? syear = schoolYear == -1 ? (int?)null : schoolYear;
            int? sterm = term == -1 ? (int?)null : term;
            return scesrLogic.SaveOrUpdateRecord(list, causeID, clsID, 3, year, month, syear, sterm, Common.GetUserInfo().UID, SchoolMark);
        }
        catch (Exception)
        {

            throw;
        }
    }

    private static IList<Items> ConvertJson(string jsonStr)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        return jss.Deserialize<IList<Items>>(jsonStr);
    }
    protected void btnReflesh_Click(object sender, EventArgs e)
    {
        tblHead.Rows.Clear();
        tblHead.Rows.Clear();
        BindHeadTable();
        BindBodyTable();
    }

    [WebMethod]
    public static string GetExcel(ExcelTableCell[][] cells, int causeID)
    {
        string temp_path = HttpContext.Current.Server.MapPath("../../../");
        string save_path = temp_path + "download\\" + ExcelFileName + ".xls";
        HttpContext.Current.Session["filepath"] = save_path;
        ExcelUtil.ExcelExport(save_path, ConvertToCause(causeID) + "学分报表", 2, 0, cells);
        return "";
    }

    private static string ConvertToCause(int causeID)
    {
        return Container<IGlobalCauseInfoLogic>.Instance.FindById(causeID).CauseName;
    }
}
